package com.hjieli.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Random;

import com.google.gson.JsonObject;

public class WeixinUtil {
	private final static String ENCODE = "UTF-8"; 
	public static String getJsapiTicketConfig(String appId,String JsapiTicket,String url) {
		JsonObject object = new JsonObject();
		
		object.addProperty("appId", appId);
		object.addProperty("timestamp", System.currentTimeMillis()/1000);
		object.addProperty("nonceStr", getRandomString(16));
		object.addProperty("jsapi_ticket", JsapiTicket);
		object.addProperty("url", getURLDecoderString(url));
		
		String signature = "jsapi_ticket=" + object.get("jsapi_ticket").getAsString();
		signature += "&noncestr=" + object.get("nonceStr").getAsString();
		signature += "&timestamp=" + object.get("timestamp").getAsString();
		signature += "&url=" + object.get("url").getAsString();
		
		String sign = null;
		sign = SHA1(signature);
		
		object.addProperty("signature", sign);
		object.remove("jsapi_ticket");
		object.remove("url");
		
		return object.toString();
	}
	
	public static String getURLDecoderString(String str) {
        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLDecoder.decode(str, ENCODE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
	
	private static String getRandomString(int length) { //length表示生成字符串的长度  
	    String base = "abcdefghijklmnopqrstuvwxyz0123456789";     
	    Random random = new Random();
	    StringBuffer sb = new StringBuffer();
	    for (int i = 0; i < length; i++) {     
	        int number = random.nextInt(base.length());     
	        sb.append(base.charAt(number));     
	    }     
	    return sb.toString();     
	 }
	
//	private static String SHA1(String decript) throws NoSuchAlgorithmException, UnsupportedEncodingException {
//		MessageDigest crypt = MessageDigest.getInstance("SHA-1");
//        crypt.reset();
//        crypt.update(decript.getBytes("UTF-8"));
//        
//        Formatter formatter = new Formatter();
//        for (byte b : crypt.digest())
//        {
//            formatter.format("%02x", b);
//        }
//        String result = formatter.toString();
//        formatter.close();
//        
//        return result;
//    }
	
	private static final char[] HEX = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    
    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        // 把密文转换成十六进制的字符串形式  
        for (int j = 0; j < len; j++) {
            buf.append(HEX[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }
    public static String SHA1(String str) {
        if (str == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.update(str.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
	
    public static void main(String[] args) {
		String test = "jsapi_ticket=HoagFKDcsGMVCIY2vOjf9ouNSUnEFl6zht3WQD0KMiYArDp9FN5foRr_p-7xnc0u8qQ-AscV3h9xKZ0aNqOQ1g&noncestr=8s0yobts3gjebmca&timestamp=1552433381&url=http%3A%2F%2F127.0.0.1%3A8080%2F";
		System.out.println(SHA1(test));
	}
	
}
